package controller

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx"
	"io"
	"net/http"
	"time"
	"tino_manager/dao"
	"tino_manager/dto"
	"tino_manager/middleware"
	"tino_manager/public"
)

type ReservationController struct {
}

func ReservationRegister(group *gin.RouterGroup) {
	reservation := &ReservationController{}
	//创建预约
	group.POST("/add", middleware.WeAppMiddleware(), reservation.Add)
	//预约列表
	group.GET("/page", middleware.WeAppMiddleware(), reservation.Page)
	//普通用户获取预约列表
	group.GET("/mine_page", middleware.WeAppMiddleware(), reservation.MinePage)
	//判断时间段是否已被预约
	group.POST("/validate_time", middleware.WeAppMiddleware(), reservation.ValidateTime)
	//获取预约详情
	group.GET("/detail", reservation.Detail)
	//删除预约
	group.POST("/remove", middleware.WeAppMiddleware(), reservation.Remove)
	//管理员删除预约
	group.POST("/delete", middleware.WeAppMiddleware(), reservation.Delete)
	//修改预约
	group.POST("/update", middleware.WeAppMiddleware(), reservation.Update)
	//清空场地预约记录
	group.POST("/clear_reservation", middleware.WeAppMiddleware(), reservation.Clear)
	//预约记录审批列表
	group.GET("/audit_page", middleware.WeAppMiddleware(), reservation.AuditPage)
	//管理员审核预约
	group.POST("/audit", middleware.WeAppMiddleware(), reservation.Audit)
	//预约数据导出
	group.GET("/export", middleware.WeAppMiddleware(), reservation.Export)
	//评价
	group.POST("/comment", middleware.WeAppMiddleware(), reservation.Comment)
	//取消预约
	group.POST("/cancel", middleware.WeAppMiddleware(), reservation.Cancel)
	//获取本人待打卡列表
	group.GET("/mine_wait_check", middleware.WeAppMiddleware(), reservation.MineWaitCheck)
	//打卡
	group.POST("/check_in", middleware.WeAppMiddleware(), reservation.CheckIn)
}

func (r *ReservationController) Add(c *gin.Context) {
	params := &dto.ReservationAddInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("预约失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("预约失败"), true)
		return
	}
	user := &dao.User{}
	if result := tx.Where("open_id = ?", value).First(user); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败，请稍后重试"), true)
		return
	}
	//查询时间段是否已经被预约
	//if result := tx.Model(&dao.Reservation{}).Where("begin_time >= ? AND end_time <= ? AND site_id = ? AND is_delete = 0 AND status = 0", params.BeginTime, params.EndTime, params.SiteId).Or("begin_time < ? AND end_time > ? AND site_id = ? AND is_delete = 0 AND status = 0", params.BeginTime, params.BeginTime, params.SiteId).Or("begin_time < ? AND end_time > ? AND site_id = ? AND is_delete = 0 AND status = 0", params.EndTime, params.EndTime, params.SiteId).First(&dao.Reservation{}); result.RowsAffected != 0 {
	//	middleware.ResponseError(c, 500, errors.New("此时间段已被预约"), true)
	//	return
	//}
	reservation := &dao.Reservation{
		SiteId:    params.SiteId,
		SiteName:  params.SiteName,
		Title:     params.Title,
		Corporate: params.Corporate,
		BeginTime: params.BeginTime,
		//EndTime:       params.EndTime,
		Contact:       params.Contact,
		Phone:         params.Phone,
		PeopleNum:     params.PeopleNum,
		Options:       []byte(params.Options),
		Remark:        params.Remark,
		MeetingStatus: params.MeetingStatus,
		MeetingMark:   params.MeetingMark,
		ExplainStatus: params.ExplainStatus,
		ExplainMark:   params.ExplainMark,
		CareStatus:    params.CareStatus,
		CareMark:      params.CareMark,
		CreatedBy:     fmt.Sprintf("%v", value),
	}
	if err := reservation.Save(c, tx); err != nil {
		middleware.ResponseError(c, 500, errors.New("预约失败"), true)
		return
	}
	if user.OpenMessageStatus == 1 {
		//给客户发送预约消息
		public.SendReservationTemplateMessage(user.MessageOpenId, params.BeginTime, params.Contact, "待审核", "场地预约")
	}
	//给管理员发送消息
	public.SentToManagerTemplateMessage(tx, "", params.BeginTime, params.Contact, "待审核", "场地预约")
	middleware.ResponseSuccess(c, reservation.Id, true)
}

func (r *ReservationController) ValidateTime(c *gin.Context) {
	params := &dto.ReservationValidateTimeInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	query := tx.Model(&dao.Reservation{}).Where("begin_time >= ? AND end_time <= ? AND site_id = ? AND is_delete = 0 AND status = 0", params.BeginTime, params.EndTime, params.SiteId).Or("begin_time < ? AND end_time > ? AND site_id = ? AND is_delete = 0 AND status = 0", params.BeginTime, params.BeginTime, params.SiteId).Or("begin_time < ? AND end_time > ? AND site_id = ? AND is_delete = 0 AND status = 0", params.EndTime, params.EndTime, params.SiteId)
	//查询时间段是否已经被预约
	reservation := &dao.Reservation{}
	if result := query.First(reservation); result.RowsAffected != 0 {
		if params.ReservationId != "" {
			fmt.Println(params.ReservationId, fmt.Sprintf("%d", reservation.Id))
			if params.ReservationId != fmt.Sprintf("%d", reservation.Id) {
				middleware.ResponseError(c, 500, errors.New("此时间段已被预约"), true)
				return
			}
		} else {
			middleware.ResponseError(c, 500, errors.New("此时间段已被预约"), true)
			return
		}
	}
	middleware.ResponseSuccess(c, "可以预约", false)
}

func (r *ReservationController) Page(c *gin.Context) {
	params := &dto.ReservationMinePageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	total := int64(0)
	offset := (params.PageNumber - 1) * params.PageSize
	var list []dao.Reservation
	query := tx.WithContext(c).Model(&dao.Reservation{}).Order("create_at desc")
	if params.KeyWord != "" {
		query = query.Where("title LIKE ?", "%"+params.KeyWord+"%")
	}
	if params.UserId != "" {
		query = query.Where("created_by = ? AND is_delete=0", params.UserId)
	} else {
		if params.Type == "1" {
			//最新修改
			//query = query.Where("create_at")
		}
		if params.Type == "2" {
			//最新预约
		}
		if params.Type == "3" {
			//用户删除
			query.Where("is_manager_delete = ? AND is_delete = ?", 0, 1)
		} else {
			query = query.Where("is_delete = 0")
		}
	}

	if params.SiteId != "" {
		query = query.Where("site_id = ?", params.SiteId)
	}
	query.Count(&total)
	if err := query.Limit(params.PageSize).Offset(offset).Find(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败"), true)
		return
	}
	out := &dto.ReservationPageOutput{
		Total: total,
	}
	for _, item := range list {
		out.List = append(out.List, dto.ReservationInfo{
			Id:            fmt.Sprintf("%d", item.Id),
			SiteId:        item.SiteId,
			SiteName:      item.SiteName,
			Title:         item.Title,
			Corporate:     item.Corporate,
			BeginTime:     item.BeginTime,
			EndTime:       item.EndTime,
			Contact:       item.Contact,
			Phone:         item.Phone,
			PeopleNum:     item.PeopleNum,
			MeetingStatus: item.MeetingStatus,
			MeetingMark:   item.MeetingMark,
			ExplainStatus: item.ExplainStatus,
			ExplainMark:   item.ExplainMark,
			CareStatus:    item.CareStatus,
			Options:       string(item.Options),
			CareMark:      item.CareMark,
			AuditStatus:   item.AuditStatus,
			AuditRemark:   item.AuditRemark,
			CreatedBy:     item.CreatedBy,
			Status:        item.Status,
			Comment:       item.Comment,
			Star:          item.Star,
			DeleteRemark:  item.DeleteRemark,
			IsDelete:      item.IsDelete,
			UpdatedAt:     item.UpdatedAt.Format("2006-01-02 15:04:05"),
			CreatedAt:     item.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}
	middleware.ResponseSuccess(c, out, true)
}

func (r *ReservationController) MinePage(c *gin.Context) {
	params := &dto.ReservationMinePageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	total := int64(0)
	offset := (params.PageNumber - 1) * params.PageSize
	var list []dao.Reservation
	query := tx.WithContext(c).Model(&dao.Reservation{}).Where("is_delete=0 AND created_by = ?", value).Order("create_at desc")

	query.Count(&total)
	if err := query.Limit(params.PageSize).Offset(offset).Find(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败"), true)
		return
	}
	out := &dto.ReservationPageOutput{
		Total: total,
	}
	for _, item := range list {
		out.List = append(out.List, dto.ReservationInfo{
			Id:            fmt.Sprintf("%d", item.Id),
			SiteId:        item.SiteId,
			SiteName:      item.SiteName,
			Title:         item.Title,
			Corporate:     item.Corporate,
			BeginTime:     item.BeginTime,
			EndTime:       item.EndTime,
			Contact:       item.Contact,
			Phone:         item.Phone,
			PeopleNum:     item.PeopleNum,
			Options:       string(item.Options),
			MeetingStatus: item.MeetingStatus,
			CheckStatus:   item.CheckStatus,
			MeetingMark:   item.MeetingMark,
			ExplainStatus: item.ExplainStatus,
			ExplainMark:   item.ExplainMark,
			CareStatus:    item.CareStatus,
			CareMark:      item.CareMark,
			CreatedBy:     item.CreatedBy,
			Comment:       item.Comment,
			Star:          item.Star,
			Status:        item.Status,
			IsDelete:      item.IsDelete,
			AuditStatus:   item.AuditStatus,
			AuditRemark:   item.AuditRemark,
			UpdatedAt:     item.UpdatedAt.Format("2006-01-02 15:04:05"),
			CreatedAt:     item.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}
	middleware.ResponseSuccess(c, out, true)
}

func (r *ReservationController) Detail(c *gin.Context) {
	params := &dto.ReservationDetailInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取详情失败"), true)
		return
	}
	reservation := &dao.Reservation{}
	if result := tx.Where(map[string]interface{}{
		"id": params.Id,
	}).First(reservation); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("获取详情失败"), true)
		return
	}
	middleware.ResponseSuccess(c, dto.ReservationInfo{
		Id:            fmt.Sprintf("%d", reservation.Id),
		SiteId:        reservation.SiteId,
		SiteName:      reservation.SiteName,
		Title:         reservation.Title,
		Corporate:     reservation.Corporate,
		BeginTime:     reservation.BeginTime,
		EndTime:       reservation.EndTime,
		Contact:       reservation.Contact,
		Phone:         reservation.Phone,
		PeopleNum:     reservation.PeopleNum,
		Options:       string(reservation.Options),
		MeetingStatus: reservation.MeetingStatus,
		MeetingMark:   reservation.MeetingMark,
		ExplainStatus: reservation.ExplainStatus,
		ExplainMark:   reservation.ExplainMark,
		AuditStatus:   reservation.AuditStatus,
		AuditRemark:   reservation.AuditRemark,
		CareStatus:    reservation.CareStatus,
		CareMark:      reservation.CareMark,
		CreatedBy:     reservation.CreatedBy,
		Status:        reservation.Status,
		IsDelete:      reservation.IsDelete,
		UpdatedAt:     reservation.UpdatedAt.Format("2006-01-02 15:04:05"),
		CreatedAt:     reservation.CreatedAt.Format("2006-01-02 15:04:05"),
	}, false)
}
func (r *ReservationController) Update(c *gin.Context) {
	params := &dto.ReservationUpdateInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败，请稍后重试"), true)
		return
	}
	//查询时间段是否已经被预约
	//if result := tx.Model(&dao.Reservation{}).Where("begin_time >= ? AND end_time <= ? AND site_id = ? AND is_delete = 0 AND status = 0 AND id <> ?", params.BeginTime, params.EndTime, params.SiteId, params.Id).Or("begin_time < ? AND end_time > ? AND site_id = ? AND is_delete = 0 AND status = 0 AND id <> ?", params.BeginTime, params.BeginTime, params.SiteId, params.Id).Or("begin_time < ? AND end_time > ? AND site_id = ? AND is_delete = 0 AND status = 0 AND id <> ?", params.EndTime, params.EndTime, params.SiteId, params.Id).First(&dao.Reservation{}); result.RowsAffected != 0 {
	//	middleware.ResponseError(c, 500, errors.New("此时间段已被预约"), true)
	//	return
	//}
	user := &dao.User{}
	if result := tx.Where("open_id = ?", value).First(user); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败，请稍后重试"), true)
		return
	}
	if result := tx.Model(&dao.Reservation{}).Where(map[string]interface{}{
		"id": params.Id,
	}).Select("site_id", "site_name", "title", "corporate", "begin_time", "options", "end_time", "contact", "remark", "phone", "audit_status", "audit_remark", "people_num", "meeting_status", "meeting_mark", "explain_status", "explain_mark", "care_status", "care_mark").Updates(&dao.Reservation{
		SiteId:    params.SiteId,
		SiteName:  params.SiteName,
		Title:     params.Title,
		Corporate: params.Corporate,
		BeginTime: params.BeginTime,
		//EndTime:       params.EndTime,
		Contact:       params.Contact,
		Phone:         params.Phone,
		PeopleNum:     params.PeopleNum,
		Options:       []byte(params.Options),
		Remark:        params.Remark,
		MeetingStatus: params.MeetingStatus,
		MeetingMark:   params.MeetingMark,
		ExplainStatus: params.ExplainStatus,
		ExplainMark:   params.ExplainMark,
		AuditRemark:   "",
		AuditStatus:   0,
		CareStatus:    params.CareStatus,
		CareMark:      params.CareMark,
	}); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败，请稍后重试"), true)
		return
	}
	if user.OpenMessageStatus == 1 {
		//给客户发送预约消息
		public.SendReservationTemplateMessage(user.MessageOpenId, params.BeginTime, params.Contact, "待审核", "场地预约")
	}
	//给管理员发送消息
	public.SentToManagerTemplateMessage(tx, "", params.BeginTime, params.Contact, "待审核", "场地预约")
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (r *ReservationController) Remove(c *gin.Context) {
	params := &dto.ReservationRemoveInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Reservation{}).Where(map[string]interface{}{
		"id":         params.Id,
		"created_by": value,
	}).Updates(&dao.Reservation{
		IsDelete:     1,
		DeleteRemark: params.DeleteRemark,
	}); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("删除失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (r *ReservationController) Delete(c *gin.Context) {
	params := &dto.ReservationRemoveInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Reservation{}).Where(map[string]interface{}{
		"id": params.Id,
	}).Updates(&dao.Reservation{
		IsDelete:        1,
		IsManagerDelete: 1,
		DeleteRemark:    params.DeleteRemark,
	}); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("删除失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (r *ReservationController) Clear(c *gin.Context) {
	params := &dto.ReservationClearInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Reservation{}).Where("site_id = ? AND is_delete = 0", params.SiteId).Updates(&dao.Reservation{
		IsDelete:        1,
		IsManagerDelete: 1,
	}); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (r *ReservationController) AuditPage(c *gin.Context) {
	params := &dto.AuditPageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	total := int64(0)
	offset := (params.PageNumber - 1) * params.PageSize
	var list []dao.Reservation
	query := tx.WithContext(c).Model(&dao.Reservation{}).Order("create_at desc")
	if params.KeyWord != "" {
		query = query.Where("title LIKE ? OR site_name LIKE ?", "%"+params.KeyWord+"%", "%"+params.KeyWord+"%")
	}
	if params.AuditStatus != "" {
		query = query.Where("audit_status = ? AND is_delete = 0 AND status = 0", params.AuditStatus)
	}
	if params.Status != "" {
		query = query.Where("status = ? AND is_delete = 0 AND audit_status = 1", params.Status)
	}
	if params.IsDelete != "" {
		query = query.Where("is_delete = ? AND status = 0", params.IsDelete)
	}
	query.Count(&total)
	if err := query.Limit(params.PageSize).Offset(offset).Find(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败"), true)
		return
	}
	out := &dto.ReservationPageOutput{
		Total: total,
	}
	for _, item := range list {
		out.List = append(out.List, dto.ReservationInfo{
			Id:            fmt.Sprintf("%d", item.Id),
			SiteId:        item.SiteId,
			SiteName:      item.SiteName,
			Title:         item.Title,
			Corporate:     item.Corporate,
			BeginTime:     item.BeginTime,
			EndTime:       item.EndTime,
			Contact:       item.Contact,
			Phone:         item.Phone,
			PeopleNum:     item.PeopleNum,
			Options:       string(item.Options),
			MeetingStatus: item.MeetingStatus,
			MeetingMark:   item.MeetingMark,
			ExplainStatus: item.ExplainStatus,
			ExplainMark:   item.ExplainMark,
			CareStatus:    item.CareStatus,
			AuditStatus:   item.AuditStatus,
			AuditRemark:   item.AuditRemark,
			CareMark:      item.CareMark,
			CreatedBy:     item.CreatedBy,
			Status:        item.Status,
			IsDelete:      item.IsDelete,
			DeleteRemark:  item.DeleteRemark,
			CancelRemark:  item.CancelRemark,
			UpdatedAt:     item.UpdatedAt.Format("2006-01-02 15:04:05"),
			CreatedAt:     item.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}
	middleware.ResponseSuccess(c, out, true)
}
func (r *ReservationController) Audit(c *gin.Context) {
	params := &dto.AuditInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	reservation := &dao.Reservation{}
	if result := tx.Where("id = ?", params.Id).First(reservation); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败，请稍后重试"), true)
		return
	}
	user := &dao.User{}
	if result := tx.Where("open_id = ?", reservation.CreatedBy).First(user); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败，请稍后重试"), true)
		return
	}
	if result := tx.Model(&dao.Reservation{}).Where(map[string]interface{}{
		"id": params.Id,
	}).Select("audit_status", "audit_remark").Updates(&dao.Reservation{
		AuditStatus: params.AuditStatus,
		AuditRemark: params.AuditRemark,
	}); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	typeName := "场地预约"
	if reservation.Status == 1 {
		typeName = "取消预约"
	}
	if user.OpenMessageStatus == 1 {
		//给客户发送预约消息
		if params.AuditStatus == 1 {
			public.SendReservationTemplateMessage(user.MessageOpenId, reservation.BeginTime, reservation.Contact, "审核通过", typeName)
		} else {
			public.SendReservationTemplateMessage(user.MessageOpenId, reservation.BeginTime, reservation.Contact, "审核拒绝", typeName)
		}
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func ToExcel(titleList []string, dataList []interface{}) (content io.ReadSeeker) {
	// 生成一个新的文件
	file := xlsx.NewFile()
	// 添加sheet页
	sheet, _ := file.AddSheet("Sheet1")
	// 插入表头
	titleRow := sheet.AddRow()
	for _, v := range titleList {
		cell := titleRow.AddCell()
		cell.Value = v
	}
	// 插入内容
	for _, v := range dataList {
		row := sheet.AddRow()
		row.WriteStruct(v, -1)
	}

	var buffer bytes.Buffer
	_ = file.Write(&buffer)
	content = bytes.NewReader(buffer.Bytes())
	return
}
func ResponseXls(c *gin.Context, content io.ReadSeeker, fileTag string) {
	fileName := fmt.Sprintf("%s%s%s.xlsx", time.Now().Format("2006-01-02 15:04:05"), `-`, fileTag)
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
	c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
}
func (r *ReservationController) Export(c *gin.Context) {

	params := &dto.ExportInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("查询失败"), true)
		return
	}
	var list []dao.Reservation
	query := tx.WithContext(c).Model(&dao.Reservation{}).Where("is_delete=0 AND status = 0").Order("create_at desc")

	if params.SiteId != "" {
		query = query.Where("site_id = ?", params.SiteId)
	}
	if err := query.Find(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败"), true)
		return
	}
	var out []interface{}
	for _, item := range list {
		out = append(out, &dto.ExportInfo{
			SiteName:  item.SiteName,
			Title:     item.Title,
			Corporate: item.Corporate,
			BeginTime: item.BeginTime,
			EndTime:   item.EndTime,
			Contact:   item.Contact,
			Phone:     item.Phone,
			PeopleNum: item.PeopleNum,
			Remark:    item.Remark,
		})
	}
	content := ToExcel([]string{"场地名称", "活动标题", "单位名称", "开始时间", "结束时间", "联系人", "手机号", "活动人数", "备注"}, out)
	ResponseXls(c, content, "导出预约数据")
}
func (r *ReservationController) Comment(c *gin.Context) {
	params := &dto.CommentInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Reservation{}).Where(map[string]interface{}{
		"id":         params.Id,
		"created_by": value,
	}).Updates(&dao.Reservation{
		Star:    params.Star,
		Comment: params.Comment,
	}); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (r *ReservationController) Cancel(c *gin.Context) {
	params := &dto.CancelInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Reservation{}).Where(map[string]interface{}{
		"id":         params.Id,
		"created_by": value,
	}).Select("status", "cancel_remark", "audit_status").Updates(&dao.Reservation{
		Status:       1,
		CancelRemark: params.CancelRemark,
		AuditStatus:  0,
	}); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("取消失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "取消成功", true)
}
func (r *ReservationController) MineWaitCheck(c *gin.Context) {
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	var list []dao.Reservation
	if err := tx.Model(&dao.Reservation{}).Where("audit_status = 1 AND check_status = 0 AND is_delete = 0 AND status = 0 AND created_by = ?", value).Find(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	var out []dto.ReservationCheckInfo
	for _, item := range list {
		site := &dao.Site{}
		tx.Model(&dao.Site{}).Where("id = ?", item.SiteId).First(site)
		out = append(out, dto.ReservationCheckInfo{
			Id:        fmt.Sprintf("%d", item.Id),
			Title:     item.Title,
			SiteName:  item.SiteName,
			SiteId:    item.SiteId,
			Address:   site.Address,
			Longitude: site.Longitude,
			Latitude:  site.Latitude,
		})
	}
	middleware.ResponseSuccess(c, out, true)
}

func (r *ReservationController) CheckIn(c *gin.Context) {
	params := &dto.CheckInInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if err := tx.Model(&dao.Reservation{}).Where("id = ? AND created_by = ?", params.Id, value).Update("check_status", 1).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "打卡成功", true)
}
